<template>
  <span>微博</span>
  <el-input v-model="weibo.content" placeholder="请输入微博内容"></el-input>
<!--  图片上传-->
  <el-upload
      v-model:file-list="fileList"
      name="file"
      action="http://localhost:8080/v1/upload"
      limit="9"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
<!--  图片上传结束-->

  <el-button type="primary" @click="insert()">发布</el-button>
</template>

<script setup>
import {ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
import router from "@/router";



//图片上传的js代码
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove= (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  let  imgUrl=uploadFile.response.data;
  axios.delete('http://localhost:8080/v1/remove?imgUrl='+imgUrl)
    .then((res)=>{
      if (res.data.code==2002){
        ElMessage.success('删除成功');
      }
    });
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
//结束



const weibo=ref({
  content:''
});

const insert=()=>{
  //存储的时候把JSOO对象转换成普通字符串存储的,取出来需要转换回去才能调用属性
  let user=localStorage.user?JSON.parse(localStorage.user):null;

  if (user==null){
    alter('请先登录');
    router.push('/login');
    return;
  }
  let imgUrls=[];
  if (fileList.value.length>0){
      for (let f of fileList.value){
        let imgUrl=f.response.data;
        console.log(f.response.code);
        imgUrls.push(imgUrl);
      }
  }
  weibo.value.imgUrls=imgUrls.toString();
  weibo.value.userId=user.id;
  console.log(weibo.value);
  axios.post('http://localhost:8080/v1/weibo/insert',qs.stringify(weibo.value))
      .then((res)=>{
        if (res.data.code==2002){
          ElMessage.success("发布成功");
          router.push('/')
        }else {
          ElMessage.error();
        }
      })
}


</script>

<style scoped>

</style>